<template>
  <view
    class="select-component"
    :class="{ 'is-active': isOpen }"
    @tap.stop="handleComponentClick"
  >
    <view class="select-trigger" @tap.stop="toggleDropdown">
      <text class="select-value">{{ displayValue }}</text>
      <text
        class="select-arrow iconfont icon-youjiantou"
        :class="{ 'is-open': isOpen }"
      ></text>
    </view>

    <view v-if="isOpen" class="select-dropdown">
      <view
        v-for="option in options"
        :key="option.value"
        class="select-option"
        :class="{ 'is-selected': isSelected(option.value) }"
        @tap.stop="handleSelect(option)"
      >
        <text>{{ option.label }}</text>
        <text
          v-if="isSelected(option.value)"
          class="iconfont icon-duihao selected-icon"
        ></text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "Select",

  props: {
    // v-model绑定值
    modelValue: {
      type: [String, Number, Array],
      default: "",
    },
    // 选项数组
    options: {
      type: Array,
      default: () => [],
      validator: (options) => {
        return options.every(
          (option) =>
            option.hasOwnProperty("label") && option.hasOwnProperty("value")
        );
      },
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 占位符
    placeholder: {
      type: String,
      default: "请选择",
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {
      isOpen: false,
    };
  },

  computed: {
    displayValue() {
      if (this.multiple) {
        if (!Array.isArray(this.modelValue) || this.modelValue.length === 0) {
          return this.placeholder;
        }
        return this.options
          .filter((option) => this.modelValue.includes(option.value))
          .map((option) => option.label)
          .join(", ");
      } else {
        const selected = this.options.find(
          (option) => option.value === this.modelValue
        );
        return selected ? selected.label : this.placeholder;
      }
    },
  },

  mounted() {
    // 添加全局点击事件监听
    wx.onAppShow(() => {
      this.setupGlobalClickListener();
    });
    this.setupGlobalClickListener();
  },

  beforeDestroy() {
    // 移除全局点击事件监听
    this.removeGlobalClickListener();
  },

  methods: {
    setupGlobalClickListener() {
      // 添加页面点击事件监听
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      if (currentPage) {
        currentPage.handlePageTap = () => {
          if (this.isOpen) {
            this.closeDropdown();
          }
        };
      }
    },

    removeGlobalClickListener() {
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      if (currentPage) {
        currentPage.handlePageTap = null;
      }
    },

    handleComponentClick(e) {
      // 阻止事件冒泡，防止触发页面的点击事件
      e.stopPropagation();
    },

    toggleDropdown() {
      if (this.disabled) return;
      this.isOpen = !this.isOpen;
    },

    handleSelect(option) {
      if (this.disabled) return;

      if (this.multiple) {
        const newValue = Array.isArray(this.modelValue)
          ? [...this.modelValue]
          : [];
        const index = newValue.indexOf(option.value);

        if (index === -1) {
          newValue.push(option.value);
        } else {
          newValue.splice(index, 1);
        }

        this.$emit("update:modelValue", newValue);
        this.$emit("change", newValue);
      } else {
        this.$emit("update:modelValue", option.value);
        this.$emit("change", option.value);
        this.closeDropdown();
      }
    },

    isSelected(value) {
      if (this.multiple) {
        return (
          Array.isArray(this.modelValue) && this.modelValue.includes(value)
        );
      }
      return this.modelValue === value;
    },

    closeDropdown() {
      this.isOpen = false;
    },
  },
};
</script>

<style lang="scss">
.select-component {
  position: relative;
  width: 100%;

  .select-trigger {
    display: flex;
    align-items: center;
    justify-content: space-between;
    min-height: 72rpx;
    padding: 0 24rpx;
    background-color: #fff;
    border: 2rpx solid #dcdfe6;
    border-radius: 8rpx;
    cursor: pointer;
    transition: all 0.2s;

    &:active {
      border-color: $primary-color;
    }
  }

  &.is-active .select-trigger {
    border-color: $primary-color;
  }

  .select-value {
    flex: 1;
    font-size: 28rpx;
    color: #606266;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .select-arrow {
    margin-left: 8rpx;
    font-size: 24rpx;
    color: #c0c4cc;
    transition: transform 0.2s;

    &.is-open {
      transform: rotate(90deg);
    }
  }

  .select-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    z-index: 1000;
    margin-top: 8rpx;
    padding: 8rpx 0;
    background-color: #fff;
    border: 2rpx solid #e4e7ed;
    border-radius: 8rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }

  .select-option {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 24rpx;
    font-size: 28rpx;
    color: #606266;
    cursor: pointer;

    &:active {
      background-color: #f5f7fa;
    }

    &.is-selected {
      color: $primary-color;
      font-weight: 500;
      background-color: #ecf5ff;
    }

    .selected-icon {
      font-size: 24rpx;
      color: $primary-color;
    }
  }
}

[data-theme="dark"] {
  .select-component {
    .select-trigger {
      background-color: #1a1a1a;
      border-color: #4c4c4c;
    }

    .select-value {
      color: #e0e0e0;
    }

    .select-arrow {
      color: #808080;
    }

    .select-dropdown {
      background-color: #1a1a1a;
      border-color: #4c4c4c;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.3);
    }

    .select-option {
      color: #e0e0e0;

      &:active {
        background-color: #2a2a2a;
      }

      &.is-selected {
        background-color: #2a2a2a;
      }
    }
  }
}
</style>
